/*
 * @Author: Wushiqi
 * @Descripttion: 公共方法
 * @Date: 2019-11-28 17:43:38
 * @LastEditor: Wushiqi
 * @LastEditTime: 2021-05-17 16:39:32
 */
import store from '@/store/index'

function getBtn(url) {
  // const menus = JSON.parse(sessionStorage.menu)
  const menus = store.state.user.menuList
  for (let i = 0; i < menus.length; i++) {
    const menu = menus[i]
    const childArray = menu.childMenuInfoTreeSet
    for (let j = 0; j < childArray.length; j++) {
      const childMenu = childArray[j]
      if (childMenu.url === url) {
        return childMenu.childButtonMenuInfoTreeSet
      }
    }
  }
}

import Vue from 'vue'
// 禁止输入特殊字符
Vue.prototype.validForbid = function(value) {
  if (value) {
    value = value.replace(/[`~!@#$%^&*()+=<>?:"{}|\\,./;'·~！@#￥%……&*——+={}|《》？：“”【】、；‘’，。、]/g, '').replace(/\s/g, '')
  }
  return value
}
// 禁止输入中文
Vue.prototype.ChForbid = function(value) {
  if (value) {
    value = value.replace(/[`~!@#$%^&*()\-+=<>?:"{}|,./;'·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、]/g, '').replace(/[^\w\/]/ig, '').replace(/\s/g, '')
  }
  return value
}

// 自适应表格列宽
Vue.prototype.flexColumnWidth = function(str, tableData, maxWidth, minWidth = 80) {
  // str为该列的字段名(传字符串);tableData为该表格的数据源(传变量);
  // flag为可选值，可不传该参数,传参时可选'max'或'equal',默认为'max'
  // flag为'max'则设置列宽适配该列中最长的内容,flag为'equal'则设置列宽适配该列中第一行内容的长度。
  const flag = 'max'
  str = str + ''
  let columnContent = ''
  if (!tableData || !tableData.length || tableData.length === 0 || tableData === undefined) {
    return minWidth + 'px'
  }
  if (!str || !str.length || str.length === 0 || str === undefined) {
    return
  }
  if (flag === 'equal') {
    // 获取该列中第一个不为空的数据(内容)
    for (let i = 0; i < tableData.length; i++) {
      if (tableData[i][str].length > 0) {
        // console.log('该列数据[0]:', tableData[0][str])
        columnContent = tableData[i][str]
        break
      }
    }
  } else {
    // 获取该列中最长的数据(内容)
    let index = 0
    for (let i = 0; i < tableData.length; i++) {
      if (tableData[i][str] === null) {
        // return
        tableData[i][str] = ''
      }
      const now_temp = tableData[i][str] + ''
      const max_temp = tableData[index][str] + ''
      if (now_temp.length > max_temp.length) {
        index = i
      }
    }
    columnContent = tableData[index][str]
  }
  // 以下分配的单位长度可根据实际需求进行调整
  let flexWidth = 0
  for (const char of columnContent) {
    if ((char >= 'A' && char <= 'Z') || (char >= 'a' && char <= 'z')) {
      // 如果是英文字符，为字符分配8个单位宽度
      flexWidth += 10
    } else if (char >= '\u4e00' && char <= '\u9fa5') {
      // 如果是中文字符，为字符分配15个单位宽度
      flexWidth += 15
    } else {
      // 其他种类字符，为字符分配8个单位宽度
      flexWidth += 9
    }
  }
  if (flexWidth < minWidth) {
    // 设置最小宽度
    flexWidth = minWidth
  }
  if (maxWidth && flexWidth > maxWidth) {
    // 设置最大宽度
    flexWidth = maxWidth
  }
  return flexWidth + 'px'
}

// pdf预览、图片预览 - url转换
function getObjectURL(file) {
  let url = null
  if (window.createObjectURL !== undefined) { // basic
    url = window.createObjectURL(file)
  } else if (window.webkitURL !== undefined) { // webkit or chrome
    try {
      url = window.webkitURL.createObjectURL(file)
    } catch (error) {
      console.log(error)
    }
  } else if (window.URL !== undefined) { // mozilla(firefox)
    try {
      url = window.URL.createObjectURL(file)
    } catch (error) {
      console.log(error)
    }
  }
  return url
}

// 计算页面表格高度
function getTableHeight(showQuery, btnList) {
// function getTableHeight(queryHeight, btnHeight) {
  const fixHeight = 84 + 7 + 33
  const queryHeight = showQuery ? 41 : 0
  const btnHeight = !btnList || btnList.length === 0 ? 0 : 43
  const tableHeight = document.body.clientHeight - fixHeight - queryHeight - btnHeight
  return tableHeight
}

// 表单验证
import { validSpecialWord, validIcon, validMenuUrl, validChinese, validPhone, isNumber } from '@/utils/validate.js'
function validateForm() {
  return {
    // 禁止特殊字符
    specialWord: (rule, value, callback) => {
      if (!value || value === '') {
        callback()
      } else if (validSpecialWord(value)) {
        callback(new Error('*不支持特殊字符'))
      } else {
        callback()
      }
    },
    // 图标
    icon: (rule, value, callback) => {
      if (!value || value === '') {
        callback()
      } else if (validIcon(value)) {
        callback(new Error('*请输入正确的图标'))
      } else {
        callback()
      }
    },
    // 菜单的url
    menuUrl: (rule, value, callback) => {
      if (!value || value === '') {
        callback()
      } else if (validMenuUrl(value)) {
        callback(new Error('*请输入正确的接口路径'))
      } else {
        callback()
      }
    },
    // 不允许输入中文
    Chinese: (rule, value, callback) => {
      if (!value || value === '') {
        callback()
      } else if (validChinese(value)) {
        callback(new Error('*不允许输入汉字'))
      } else {
        callback()
      }
    },
    // 电话号码
    phone: (rule, value, callback) => {
      if (!value || value === '') {
        callback()
      } else if (!validPhone(value)) {
        callback(new Error('*请输入正确的电话号码'))
      } else {
        callback()
      }
    },
    number: (rule, value, callback) => {
      if (!value || value === '') {
        callback()
      } else if (!isNumber(value)) {
        callback(new Error('*请输入数字'))
      } else {
        callback()
      }
    }
  }
}

import axios from 'axios'
import qs from 'qs'
import { message } from '../common/Message'
// 文件下载
function downloadRequest(url, params, method) {
  return new Promise((resolve, reject) => {
    if (method === 'GET') {
      axios({
        method,
        url,
        params,
        paramsSerializer: params => { return qs.stringify(params, { arrayFormat: 'brackets' }) },
        responseType: 'blob'
      }).then(response => { resolve(response) }).catch(error => { reject(error) })
    } else {
      axios({
        method,
        url,
        data: params,
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, // 将传给后台的数据转换成FormData
        transformRequest: [function(data) { // 对传递的数据进行格式转换，以便传递给后台
          data = qs.stringify(data)
          return data
        }],
        responseType: 'blob'
      }).then(response => { resolve(response) }).catch(error => { reject(error) })
    }
  })
}
function download(url, params, method = 'GET') {
  return new Promise((resolve, reject) => {
    downloadRequest(url, params, method).then(response => {
      if (response.data.type === 'application/octet-stream') {
        const fileName = response.headers['content-disposition'].split('=')[1]
        /* 兼容ie内核，360浏览器的兼容模式 */
        if (window.navigator && window.navigator.msSaveOrOpenBlob) {
          const blob = new Blob([response.data], { type: 'application/zip' })
          window.navigator.msSaveOrOpenBlob(blob, fileName)
        } else {
          /* 火狐谷歌的文件下载方式 */
          const blob = new Blob([response.data], { type: 'application/zip' })
          const url = window.URL.createObjectURL(blob)
          const link = document.createElement('a') // 创建a标签
          link.href = url
          link.download = decodeURI(fileName)
          link.click()
          URL.revokeObjectURL(url) // 释放内存
        }
        resolve(response)
      } else {
        const reader = new FileReader()
        reader.onload = function(event) {
          const msg = JSON.parse(reader.result).data
          message.error(msg) // 将错误信息显示出来
        }
        reader.readAsText(response.data)
        resolve(response)
      }
    }).catch(error => {
      message.error('' + error)
      reject(error)
    })
  })
}

/*
 * @Author: cxy
 * @Descripttion: 深拷贝
 * @Date: 2021-04.26
 */
function typeOf(obj) {
  const toString = Object.prototype.toString
  const map = {
    '[object Boolean]': 'boolean',
    '[object Number]': 'number',
    '[object String]': 'string',
    '[object Function]': 'function',
    '[object Array]': 'array',
    '[object Date]': 'date',
    '[object RegExp]': 'regExp',
    '[object Undefined]': 'undefined',
    '[object Null]': 'null',
    '[object Object]': 'object'
  }
  return map[toString.call(obj)]
}
function deepCopy(data) {
  const t = typeOf(data)
  let o

  if (t === 'array') {
    o = []
  } else if (t === 'object') {
    o = {}
  } else {
    return data
  }

  if (t === 'array') {
    for (let i = 0; i < data.length; i++) {
      o.push(deepCopy(data[i]))
    }
  } else if (t === 'object') {
    for (const i in data) {
      o[i] = deepCopy(data[i])
    }
  }
  return o
}

export default {
  getBtn,
  getObjectURL,
  getTableHeight,
  validateForm,
  download,
  deepCopy
}
